<script setup lang="tsx">
import { NButton, NTag } from 'naive-ui';
import {ref} from "vue";
import { useRoute } from 'vue-router';
import {fetchBatchHospCategory, fetchGetAllCategory} from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { deleteFlagRecord } from '@/constants/business';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useRouterPush } from '@/hooks/common/router';

// 路由
const { routerPushByKey } = useRouterPush();
// 正确初始化 categoryMap 为一个 ref
const categoryMap = ref<Record<string, string>>({});
let error; // 使用 let 声明并初始化
const appStore = useAppStore();
// 获取到进入页面的ID
const route = useRoute();

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  immediate: undefined,
  apiFn: async () => {
    const response = await fetchBatchHospCategory(useRoute().params.id as string);
    const result = await fetchGetAllCategory();
    error = result.error;
    // 更新 categoryMap 的值
    categoryMap.value = result.data.reduce((map, category) => {
      map[category.id] = category.name;
      return map;
    }, {});
    console.log('Fetched Data:', categoryMap.value);
    return response;
  },
  showTotal: true,
  columns: () => [
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64
    },
    {
      key: 'categoryId',
      title: $t('page.check.category.name'),
      align: 'center',
      render: row => {
        // 使用 categoryId 映射到对应的 I18nKey
        const categoryNameKey = categoryMap.value[row.categoryId];
        // 使用 $t 方法获取翻译后的名称
        return categoryNameKey ? $t(categoryNameKey) : '-';
      }
    },
    {
      key: 'score',
      title: $t('page.check.hosp.category.score'),
      align: 'center'
    },
    {
      key: 'deleteFlag',
      title: $t('page.check.category.deleteFlag'),
      align: 'center',
      render: row => {
        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          1 : 'success',
          0 : 'warning'
        };
        const label = $t(deleteFlagRecord[row.deleteFlag ? 1 : 0]);
        return <NTag type={tagMap[row.deleteFlag ? 1 : 0]}>{label}</NTag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: row => {
        if(!row.deleteFlag){
          return (
            <NButton type="primary" size="small" onClick={() => handleEnterScore(row)}>
              进入打分
            </NButton>
          );
        }
      }
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

// 示例事件处理函数
function handleEnterScore(row: any) {
  console.log('进入打分:', row);
  routerPushByKey('score', { params: { id: row.id } })
    .then(() => {
      console.log('成功跳转到打分界面');
    })
    .catch(error => {
      console.error('跳转失败:', error);
    });
}


</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">

    <NCard :title="$t('page.batch.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
